import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 公开路由
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login/Login.vue'),
      meta: { public: true } // 标记为公开路由
    },

    // 基础布局路由
    {
      path: '/',
      name: 'home',
      //component: () => import('../layouts/MainLayout.vue'), // 布局组件提升到父级
      meta: { requiresAuth: true },
      children: [
        // 所有角色可访问的首页
        {
          path: '',
          name: 'dashboard',
          component: () => import('../layouts/MainLayout.vue'),
          meta: { roles: ['admin', 'doctor'] }
        },

        // 管理员专属路由
        {
          path: 'companies',
          name: 'company-management',
          component: () => import('../views/company/CompanyManagement.vue'),
          meta: { roles: ['admin'] }
        },
        {
          path: 'policies',
          name: 'policy-management',
          component: () => import('../views/policy/PolicyManagement.vue'),
          meta: { roles: ['admin'] }
        },
        {
          path: 'materials',
          name: 'Material',
          component: () => import('../views/Material/MaterialView.vue'),
          meta: { roles: ['admin'] }
        },
        {
          path: 'doctors',
          name: 'Doctor',
          component: () => import('../views/Doctor/DoctorView.vue'),
          meta: { roles: ['admin'] }
        },
        {
              path: 'cities',
              name: 'City',
              component: () => import('../views/City/components/CityList.vue'),
              meta: { roles: ['admin'] }
        }


      ]
    }
  ]
})

// 增强版导航守卫
router.beforeEach((to, from, next) => {
  // 1. 检查是否公开路由
  if (to.meta.public) {
    return next()
  }

  // 2. 认证检查
  const isLoggedIn = localStorage.getItem('token') // 改用token验证
  if (to.meta.requiresAuth && !isLoggedIn) {
    return next('/login')
  }

  // 3. 角色权限检查
  const userRole = localStorage.getItem('userRole') // 从登录响应中存储的角色
  if (to.meta.roles && !to.meta.roles.includes(userRole)) {
    // 无权限则跳转首页（可根据需求改为403页面）
    alert('您没有访问该页面的权限')
    return next('/')
  }

  next()
})

export default router